"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 服务端工具
Case Name   : 收集现在操作系统的状态信息，收集2次间隔2秒
Create At   : 2021/02/08
Owner       : @qumin20145
Description :
    1.使用cfe工具注入故障
    2.创建收集内容的配置文件
    3.收集现在操作系统的状态信息，收集2次间隔2秒
    4.清除故障
    5.删除创建收集内容的配置文件
Expect      :
    1.故障注入完成
    2.配置文件写入完成
    3.收集成功
    4.故障清除成功
    5.删除成功
History     :
    Modified by @wan005 2021/10/19: 修改线程调用方式
"""

import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.ComThread import ComThread
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import RestartDbCluster

Primary_SH = CommonSH('PrimaryDbUser')
nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')


@RestartDbCluster(*nodes_tuple)
class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(
            '-----Opengauss_Function_Tools_gs_collector_Case0031start-----')
        self.pri_root = Node('PrimaryRoot')
        self.dbusernode = Node('PrimaryDbUser')
        self.constant = Constant()
        self.com = Common()
        self.path = os.path.join(macro.DB_INSTANCE_PATH, 'collector_config')
        self.result_path = os.path.join(macro.DB_INSTANCE_PATH,
                                        'collector_result')

        status = Primary_SH.getDbClusterStatus('detail')
        self.log.info(status)
        self.assertTrue("Normal" in status or "Degraded" in status)


    def test_server_tools1(self):
        self.log.info('----步骤1：利用cfe工具构造cpu压力100%----')
        self.log.info("----获取cpu个数----")
        shell_cmd = "cat /proc/cpuinfo |grep 'processor'|wc -l"
        self.log.info(shell_cmd)
        cpu_num = self.pri_root.sh(shell_cmd).result()
        self.log.info(cpu_num)

        self.log.info("----利用cfe工具构造cpu压力100%----")
        # 因执行该指令后不会退出，所以使用启线程的方式，在主线程结束后会退出该子线程
        inject_cmd = f"rCPU_Overloadal (cpuid1, cpuid2, usage) " \
            f"values(0, {int(cpu_num) - 1}, 100)"
        inject_thread = ComThread(self.com.cfe_inject,
                                  args=(self.pri_root, inject_cmd,))
        inject_thread.setDaemon(True)
        inject_thread.start()
        time.sleep(10)
        self.log.info("----获取cfe注入故障结果----")
        inject_thread.join(10)
        inject_result = inject_thread.get_result()
        self.log.info(inject_result)

        self.log.info('---------步骤2：创建收集内容的配置文件，文件内容是json 格式---------')
        test_str = r'''{{"Collect":[{{"TypeName": "System", "Content":
            "RunTimeInfo, HardWareInfo","Interval":"2", "Count":"2"}}]}}'''
        shell_cmd = f'''echo '{test_str}' > {self.path}'''
        self.log.info(shell_cmd)
        shell_msg = self.dbusernode.sh(shell_cmd).result()
        self.log.info(shell_msg)
        self.log.info('---------获取收集日志的时间---------')
        current_date = time.strftime("%Y%m%d", time.localtime())
        self.log.info(current_date)
        current_time = time.strftime("%Y%m%d %H:%M", time.localtime())
        self.log.info(current_time)
        self.log.info('-----步骤3：收集现在操作系统的状态信息，收集2次间隔2秒-----')
        collector_cmd = f'source {macro.DB_ENV_PATH};' \
            f'gs_collector --begin-time="{current_date} 00:00" ' \
            f'--end-time="{current_time}" ' \
            f'-C {self.path} ' \
            f'-o {self.result_path};'
        self.log.info(collector_cmd)
        collector_msg = self.dbusernode.sh(collector_cmd).result()
        self.log.info(collector_msg)
        tar_cmd = f'source {macro.DB_ENV_PATH};' \
            f'cd {self.result_path};' \
            f'tar -zxvf collector*.tar.gz;'
        self.log.info(tar_cmd)
        tar_msg = self.dbusernode.sh(tar_cmd).result()
        self.log.info(tar_msg)
        self.assertIn('Summary.log', tar_msg)
        self.assertIn('Detail.log', tar_msg)
        self.log.info("----步骤4：消除cpu压力故障----")
        clean_command = f"rCPU_Overloadal"
        clean_result = self.com.cfe_clean(self.pri_root, clean_command)
        self.log.info(clean_result)

    def tearDown(self):
        self.log.info('--------------清理环境-------------------')
        self.log.info('------------步骤:5：配置文件和结果文件-------------')
        rm_cmd = f'rm -rf {macro.DB_INSTANCE_PATH}/collector_config;' \
            f'rm -rf {macro.DB_INSTANCE_PATH}/collector_result; '
        self.log.info(rm_cmd)
        rm_msg = self.dbusernode.sh(rm_cmd).result()
        self.log.info(rm_msg)
        self.log.info("----消除cpu压力故障----")
        clean_command = f"rCPU_Overloadal"
        clean_result = self.com.cfe_clean(self.pri_root, clean_command)
        self.log.info(clean_result)
        self.log.info(
            '-----Opengauss_Function_Tools_gs_collector_Case0031finish-----')
